const formidable = require("formidable");
const path = require("path");
const fs = require("fs");
const db = require("../database");

const query = (sql, params) => {
	return new Promise((resolve, reject) => {
		db.query(sql, params, (err, result) => {
			if (err) {
				reject(err);
				return;
			}
			resolve(result);
		});
	});
};

// 获取表单数据
const getFormData = req => {
	return new Promise((resolve, reject) => {
		const form = new formidable.IncomingForm();
		form.encoding = "utf-8"; // 编码
		form.keepExtensions = true; // 保留扩展名
		form.uploadDir = path.join(__dirname, "../public/"); //文件存储路径 最后要注意加 '/' 否则会被存在public下

		form.parse(req, (err, fields, files) => {
			if (err) {
				reject(err);
				return;
			}
			resolve(files.file[0]);
		});
	});
};

const uploadImage = async req => {
	try {
		const file = await getFormData(req);
		const oldPath = file.filepath;
		const ext = file.originalFilename.split(".").pop();
		const imgName =
			new Date().getTime() + "-" + file.newFilename + "." + ext;
		const newPath = path.join(__dirname, "../public/" + imgName);

		fs.renameSync(oldPath, newPath);

		return imgName;
	} catch (err) {
		console.error(err);
		return "";
	}
};

module.exports = {
	query,
	uploadImage,
};
